package com.hw.blog.common;

import org.springframework.context.ApplicationContext;

//import com.opensymphony.webwork.ServletActionContext;

/**
 * ServletContext에 저장되어 있는 Spring 프레임워크의 ApplicationContext에 접근하는 Util제공
 * 
 * @author javajigi
 */
public class BeanUtils {
	
	/**
	 * Spring 프레임워크이 ApplicationContext에서 beanId에 해당하는 인스턴스를 반환.
	 * 
	 * @param beanId
	 * @return
	 */
	public static Object getBean( String beanId) {
		ApplicationContext applicationContext = ApplicationContextProvider.getApplicationContext();
				//WebApplicationContextUtils.getWebApplicationContext(contect, aa /*ServletActionContext.getServletContext()*/);

		if( applicationContext == null ) {
			throw new NullPointerException("Spring 프레임워크의 ApplicationContext가 초기화되지 않았습니다.");
		}
		
		
		/*
		String[] names = applicationContext.getBeanDefinitionNames();
		for (int i=0; i<names.length; i++) {
			System.out.println(names[i]);
		}
		*/
		
		return applicationContext.getBean(beanId);
	}
	
	/**
	 * Spring 프레임워크이 ApplicationContext에서 beanId에 해당하는 인스턴스를 반환.
	 * 
	 * @param beanId
	 * @return
	 */
	/*
	public static Object getBean(final HttpServletRequest request, final String beanId) throws Exception {
		Object beanObject = null;
		ServletContext sc;
		HttpSession hs;
		WebApplicationContext webApplicationContext;
		
		// DispatcherServlet으로 로딩된 context를 가져 온다.
		webApplicationContext = RequestContextUtils.getWebApplicationContext(request);
		// 빈을 검색해서 해당 빈 오브젝트를 가져 온다.
		if (webApplicationContext.containsBean(beanId)) {
			beanObject = webApplicationContext.getBean(beanId);
			return beanObject;        
		}        
		hs = request.getSession();
		sc = hs.getServletContext();
		// ContextLoaderListener으로 로딩된 context를 가져 온다.
		webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(sc);
		
		if (webApplicationContext.containsBean(beanId)) {
			beanObject = webApplicationContext.getBean(beanId);
			return beanObject;
		}
		return beanObject;
	}
	*/
	/*
	 protected WebApplicationContext findWebApplicationContext() {
		  if (this.webApplicationContext != null) {
		   // the user has injected a context at construction time -> use it
		   if (this.webApplicationContext instanceof ConfigurableApplicationContext) {
		    if (!((ConfigurableApplicationContext)this.webApplicationContext).isActive()) {
		     // the context has not yet been refreshed -> do so before returning it
		     ((ConfigurableApplicationContext)this.webApplicationContext).refresh();
		    }
		   }
		   return this.webApplicationContext;
		  }
		  String attrName = getContextAttribute();
		  if (attrName != null) {
		   return WebApplicationContextUtils.getWebApplicationContext(getServletContext(), attrName);
		  }
		  else {
		   return WebApplicationContextUtils.getWebApplicationContext(getServletContext());
		  }
		 }*/
}
